/************************************************************************************/
/*  Program name CAPFAIMP_DEPRN_DETAIL.sql                                        	*/
/*  Creater:  NIP Karen (PCCW - UniHub)                                         	*/
/*************   History   *************************                                */
/* 17 JAN, 2006   NIP Karen         First created                               	*/
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPFAIMP_DEPRN_DETAIL';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_FA_DEPRN_DETAIL;

BEGIN
	UPDATE
		FA_DEPRN_DETAIL
	SET	
		BOOK_TYPE_CODE	=	CAPBRIMP_MAPPING.RenameStr(SUBSTR(BOOK_TYPE_CODE,1,4), BOOK_TYPE_CODE)
	WHERE BOOK_TYPE_CODE IN
		(
		SELECT 
			BOOK_TYPE_CODE
		FROM 
			CRST_FA_DEPRN_DETAIL
		);
	
	FOR C1 IN Cur_F LOOP
		BEGIN		
			INSERT INTO FA_DEPRN_DETAIL
			VALUES
			(
			C1.BOOK_TYPE_CODE,
			CAPBRIMP_MAPPING.GetAssetIDMapping(C1.ASSET_ID),
			C1.PERIOD_COUNTER,
			CAPBRIMP_MAPPING.GetFADistIDMapping(C1.DISTRIBUTION_ID),
			C1.DEPRN_SOURCE_CODE,
			C1.DEPRN_RUN_DATE,
			C1.DEPRN_AMOUNT,
			C1.YTD_DEPRN,
			C1.DEPRN_RESERVE,
			C1.ADDITION_COST_TO_CLEAR,
			C1.COST,
			C1.DEPRN_ADJUSTMENT_AMOUNT,
			C1.DEPRN_EXPENSE_JE_LINE_NUM,
			C1.DEPRN_RESERVE_JE_LINE_NUM,
			C1.REVAL_AMORT_JE_LINE_NUM,
			C1.REVAL_RESERVE_JE_LINE_NUM,
			CAPBRIMP_MAPPING.GetJEHeaderIDMapping(C1.JE_HEADER_ID),
			C1.REVAL_AMORTIZATION,
			C1.REVAL_DEPRN_EXPENSE,
			C1.REVAL_RESERVE,
			C1.YTD_REVAL_DEPRN_EXPENSE,
			C1.BONUS_DEPRN_AMOUNT,
			C1.BONUS_YTD_DEPRN,
			C1.BONUS_DEPRN_RESERVE,
			C1.BONUS_DEPRN_ADJUSTMENT_AMOUNT,
			C1.BONUS_DEPRN_EXP_JE_LINE_NUM,
			C1.BONUS_DEPRN_RSV_JE_LINE_NUM
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;
	
	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/